//
//  OAuthViewController.swift
//  CXCWeibo
//
//  Created by cxc on 15/6/25.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    private let WB_Client_ID    = "3450636033"
    private let WB_Redirect_URL = "http://www.baidu.com"
    private let WB_App_secret   = "e960505682169a53aefeddd53d9779d7"
    
    lazy var webView:UIWebView? = {
        let v = UIWebView()
        v.delegate = self
        
        return v
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadOAuthPage()
    }
    /**
       * 加载授权页面
    */
    private func loadOAuthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URL)"
        let url = NSURL(string: urlString)
        webView?.loadRequest(NSURLRequest(URL: url!))
    }
    override func loadView() {
        view = webView
        
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeClick")
    }
    func closeClick(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /**使用授权码加载token*/
    private func loadAccessToken(code: String){
        // 1. urlString SSL 1.2
        let urlString = "oauth2/access_token"

        // 2. 请求参数
        let params = ["client_id": WB_Client_ID,
            "client_secret": WB_App_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_Redirect_URL]
        
        // 3. 发起网络请求
        NetworkTools.sharedNetworkTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            
            // 字典转模型
            UserAccount(dict: JSON as! [String : AnyObject]).loadUserInfo { (account, error) -> () in
                
                // 判断账户信息是否正确
                if account != nil {
                    print(account)
                    // 1. 设置全局的 account
                    sharedUserAccount = account
                    
                    // 2. 发送通知
                    // object = false 表示显示 WelcomeViewController
                    NSNotificationCenter.defaultCenter().postNotificationName(CCSwitchRootVCNotification, object: false)
            
                    
                    // 3. 关闭当前控制器
                    self.closeClick()
                    
                    return
                }
                
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
        }
    }
    
    // MARK:  - delegate
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        if !urlString.hasPrefix(WB_Redirect_URL){
            return true
        }
        
        let query = request.URL!.query!
        let codeStr = "code="
        
        //判断是否包含“code=”
        if query.hasPrefix(codeStr){
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            
            loadAccessToken(code)
        }else{
            closeClick()
        }
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}


